package com.example.capsule_netty.controller;

import com.example.capsule_netty.bean.SignBean;
import com.example.capsule_netty.configuration.Constant;
import com.example.capsule_netty.service.SignService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhuzhiming
 * @Date: 2022/5/20 17:06
 */
@RestController
public class SignController {

    @Autowired
    SignService signService;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @GetMapping("judgeHasSign/{roomName}/{userId}")
    public String judgeHasSign(@PathVariable String roomName, @PathVariable String userId) {
        return signService.doJudgeHasSign(roomName, userId);
    }


    @PostMapping("sign")
    public String sign(@RequestBody SignBean signBean) {
        return signService.doSign(signBean);
    }

    @SneakyThrows
    @PostMapping("addSignFunction")
    public String addSignFunction(@RequestBody SignBean signBean) {

        String key = signBean.getRoomName() + "sign";
        String signTime = signBean.getSignTime();
        String endTime = signBean.getEndTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = dateFormat.parse(signTime);
        Date deadlineTime = dateFormat.parse(endTime);
        redisTemplate.opsForValue().set(key, endTime, (deadlineTime.getTime() - startTime.getTime()) / 1000 % 60, TimeUnit.SECONDS);
        return Constant.SUCCESS;
    }

}
